<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>原生js实现tab</title>
		<link rel="stylesheet" type="text/css" href="../lib/reset.css"/>
		<style>
			.tab-wp {
				width: 500px;
				background-color: #ccc;
			}

			.tab-wp .tab-header {
				background-color: #fff;
			}

			.tab-wp .tab-header a {
				float: left;
				margin-right: 10px;
				width: 60px;
				height: 45px;
				text-align: center;
				line-height: 45px;
				color: #000;
			}

			.tab-wp .tab-header a.on {
				background-color: #000;
				color: #fff;
			}
			
			.tab-wp .tab-header:after {
				content: '';
				display: block;
				clear: both;
			}

			.tab-body div {
				height: 300px;
				display: none;
			}

			.tab-body div.on {
				display: block;
			}
		</style>
	</head>
	<body>

		<a href="#">7777</a>
		
		<div class="tab-wp">
			<div id="tabHeader" class="tab-header">
				<a class="on" href="javascript:void(0);">新闻</a>
				<a href="javascript:;">历史</a>
				<a href="javascript:;">政治</a>
				<a href="javascript:;">军事</a>
			</div>

			<div id="tabBody" class="tab-body">
				<div class="on">111</div>
				<div>222</div>
				<div>333</div>
				<div>444</div>
			</div>
		</div>

		<script src="js/helper.js"></script>
		<script>
			var renderTab = function() {
				var tabHeader = Helper.dom('tabHeader'),
					tabBody = Helper.dom('tabBody'),
					tabAs = tabHeader.getElementsByTagName('a'),
					tabDivs = tabBody.getElementsByTagName('div'),
					len = tabAs.length;

				if (tabAs.length != tabDivs.length) {
					alert('头部元素个数和主体元素个数不相等！');
					return;
				}

				for (var i=0; i<len; i++) {
					tabAs[i].setAttribute("index", i);

					tabAs[i].onclick = function() {
						var currIndex = this.getAttribute("index");

						for (var j=0; j<len; j++) {
							tabAs[j].className = '';
							tabDivs[j].className = '';
//							tabDivs[j].style.display = 'none';
						}

						this.className = "on";
						tabDivs[currIndex].className = 'on';
//						this.setAttribute('class', 'on');
					}
				}

			};

			renderTab();

			// window.onload = renderTab;
		</script>
		
	</body>
</html>
